package com.myMinistry.gui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.myMinistry.Helper;
import com.myMinistry.R;
import com.myMinistry.provider.MinistryContract.EntryType;
import com.myMinistry.provider.MinistryContract.Householder;
import com.myMinistry.provider.MinistryContract.Time;
import com.myMinistry.provider.MinistryService;

public class TimeEntriesListFrag extends ListFragment {
	/** Time map names */
	private static final String MAP_ID = "_id";
	private static final String MAP_TITLE = "title";
	private static final String MAP_TIME_AND_DATE = "date";
	
	private ArrayList<HashMap<String, String>> list;
	private HashMap<String, String> map;
	private SimpleAdapter adapter;
	private MinistryService database;
	private Cursor entries;
	private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat timeFormat = new SimpleDateFormat("h:mma");
	private final SimpleDateFormat displayDateFormat = new SimpleDateFormat("EEE, MMM d");
	private int publisherID = 1;
	private final Calendar date = Calendar.getInstance();
	private final Calendar displayDate = Calendar.getInstance();
	private int selectedPosition = -1;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.time_entries_listfrag, null);
		return view;
	}
	
	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
    	super.onActivityCreated(savedInstanceState);
    	
    	/** Initialize the variables */
    	list = new ArrayList<HashMap<String, String>>();
    	database = new MinistryService(getActivity().getApplicationContext());
    	
    	String[] from = new String[] {MAP_TITLE,MAP_TIME_AND_DATE};
    	int[] to = new int[] {R.id.title,R.id.timeAndDate};
    	
    	adapter = new SimpleAdapter(getActivity().getApplicationContext(), list, R.layout.time_entries_listview_item, from, to);
    	setListAdapter(adapter);
	}
	
	/** Sets publisherID and selected date to the first of the month and zero's out the time */
	public void updateList(int _publisherID, Calendar _date) {
		publisherID = _publisherID;
		date.set(Calendar.YEAR, _date.get(Calendar.YEAR));
		date.set(Calendar.MONTH, _date.get(Calendar.MONTH));
		date.set(Calendar.DATE, 1);
		
		list.clear();
		
		database.openReadable();
    	/** Get time entries for a user for the selected month */
    	entries = database.fetchTimeEntriesByPublisherAndMonth(publisherID, dateFormat.format(date.getTime()));
    	/** Loop over the results */
    	while(entries.moveToNext()) {
    		map = new HashMap<String, String>();
    		String title = "";
    		String timeAndDate = "";
    		String entryName = entries.getString(entries.getColumnIndex(EntryType.QUALIFIED_NAME));
    		String householderName = entries.getString(entries.getColumnIndex(Householder.QUALIFIED_NAME));
    		
    		String[] thedate = entries.getString(entries.getColumnIndex(Time.DATE)).split("-");
    		if(thedate.length == 3) {
    			/** We have the three numbers to make the date. */
    			displayDate.set(Calendar.YEAR, Integer.valueOf(thedate[0]));
    			/** Subtract 1 for zero based months. */
    			displayDate.set(Calendar.MONTH, Integer.valueOf(thedate[1])-1);
    			displayDate.set(Calendar.DAY_OF_MONTH, Integer.valueOf(thedate[2]));
    		}
    		
    		if(entryName != null && entryName.length() > 0)
    			title = entryName;
    		if(householderName != null && householderName.length() > 0) {
				if(title.length() > 0)
					title += " " + getActivity().getApplicationContext().getString(R.string.with) + " ";
				title += householderName;
			}
    		
    		String[] startTime = entries.getString(entries.getColumnIndex(Time.TIME_START)).split(":");
    		String[] endTime = entries.getString(entries.getColumnIndex(Time.TIME_END)).split(":");
    		Calendar time = Calendar.getInstance();
    		
    		time.set(Calendar.HOUR_OF_DAY, Integer.valueOf(startTime[0]));
    		time.set(Calendar.MINUTE, Integer.valueOf(startTime[1]));
    		
    		timeAndDate = displayDateFormat.format(displayDate.getTime()) + Helper.getDayOfMonthSuffix(displayDate.get(Calendar.DAY_OF_MONTH));
    		timeAndDate += " - " + getResources().getQuantityString(R.plurals.numberOfHours, entries.getInt(entries.getColumnIndex(Time.TOTAL_HOURS)), entries.getInt(entries.getColumnIndex(Time.TOTAL_HOURS)));
    		timeAndDate += " - " + timeFormat.format(time.getTime()).toLowerCase() + " " + getActivity().getApplicationContext().getString(R.string.to) + " ";
    		
    		time.set(Calendar.HOUR_OF_DAY, Integer.valueOf(endTime[0]));
    		time.set(Calendar.MINUTE, Integer.valueOf(endTime[1]));
    		
    		timeAndDate += timeFormat.format(time.getTime()).toLowerCase();
    		
    		/** Adding each child node to HashMap key => value */
    		map.put(MAP_ID, entries.getString(entries.getColumnIndex(Time._ID)));
    		map.put(MAP_TITLE, title);
    		map.put(MAP_TIME_AND_DATE, timeAndDate);
    		
    		list.add(map);
    	}
    	
    	entries.close();
    	database.close();
    	adapter.notifyDataSetChanged();
    }
    
    @SuppressWarnings("unchecked")
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
    	selectedPosition = position;
		HashMap<String, String> entry = (HashMap<String, String>) l.getItemAtPosition(position);
    	((TimeEntries) getActivity()).itemTouched(Integer.valueOf(entry.get(MAP_ID)));
    	
    }
    
	public void removeEntry() {
		if(selectedPosition > -1) {
	    	list.remove(selectedPosition);
			adapter.notifyDataSetChanged();
		}
		selectedPosition = -1;
	}
}